package util

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"errors"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"log"
)

var (
	NotLogin     = errors.New("user is not login")
	OverStepAuth = errors.New("user try to overstep authority")
)

func UserFilter(ctx *gin.Context) (*models.User, error) {
	session := sessions.Default(ctx)
	userInterface := session.Get("user")
	user, ok := userInterface.(models.User)
	if !ok {
		return AdminFilter(ctx)
	}
	var userNew models.User
	db.DB.Where("id = ?", user.ID).First(&userNew)
	sessionNew := sessions.Default(ctx)
	sessionNew.Set("user", userNew)
	if err := sessionNew.Save(); err != nil {
		return nil, err
	}
	log.Printf("UserFilter error:%s\n", NotLogin)
	return &userNew, nil
}

func AdminFilter(ctx *gin.Context) (*models.User, error) {
	session := sessions.Default(ctx)
	userInterface := session.Get("admin")
	user, ok := userInterface.(models.User)
	if !ok {
		ctx.AbortWithStatus(403)
		log.Printf("AdminFilter error:%s\n", NotLogin)
		return nil, NotLogin
		//return UserFilter(ctx)
	}
	if user.Authorization != models.UserAuthAdministrator {
		ctx.AbortWithStatus(500)
		log.Fatalf("AdminFilter error: id:%d try to overstep authority\n", user.ID)
		return nil, OverStepAuth
	}
	var userNew models.User
	db.DB.Where("id = ?", user.ID).First(&userNew)
	sessionNew := sessions.Default(ctx)
	sessionNew.Set("admin", userNew)
	if err := sessionNew.Save(); err != nil {
		return nil, err
	}
	return &userNew, nil
}
